<template>
  <el-drawer v-model="drawer" title="I am the title" :with-header="false">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="简介" prop="introduction">
        <el-input v-model="ruleForm.introduction" />
      </el-form-item>
      <el-form-item label="封面图片">
        <el-upload
          class="avatar-uploader"
          :http-request="customUploadRequest"
          :before-upload="beforeUpload"
          :auto-upload:="false"
          :show-file-list="false"
          :limit="1"
        >
          <img
            v-if="ruleForm.coverImg"
            :src="ruleForm.coverImg"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="valueHtml">
        <el-input v-model="ruleForm.valueHtml" type="textarea" />
      </el-form-item>
      <el-form-item label="文章分类" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择文章类型">
          <el-option
            v-for="itme in tagList"
            :key="itme.id"
            :label="itme.name"
            :value="itme.id"
          />
          <el-option label="后端开发" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item class="btn">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认发布
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">清空内容</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadRequestHandler,
  UploadRequestOptions
} from "element-plus";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getTagList, publishArticle } from "@/api/news";
import { useNewsStore } from "@/store/modules/news";
const tagList = ref<any>([]);
//定义一个响应式数组用来接收图片
const fileList = ref([]);
const ruleFormRef = ref<FormInstance>();
const newsStore = useNewsStore();
interface RuleForm {
  title: string;
  introduction: string;
  coverImg: string;
  valueHtml: string;
  type: string;
  userId: string;
  status: number;
}
console.log(newsStore.valueHtml);
const ruleForm = reactive<RuleForm>({
  title: "",
  introduction: "",
  coverImg: "",
  valueHtml: newsStore.valueHtml,
  type: "",
  userId: "a676dafd75dc11ef8f5200163e012305",
  status: 1
});

// 监听 valueHtml 的变化
watch(
  () => newsStore.valueHtml, // 监听的目标
  (newValue, oldValue) => {
    ruleForm.valueHtml = newValue;
    // 在这里执行任何你想在 valueHtml 变化时触发的逻辑
  }
);

const rules = reactive<FormRules<RuleForm>>({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  introduction: [{ required: true, message: "请输入简介", trigger: "blur" }],
  valueHtml: [{ required: true, message: "请输入内容", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }]
});
const drawer = ref(false);
const open = (): void => {
  drawer.value = true;
};
getTag();
/* 获取标签列表 */
async function getTag() {
  const res = await getTagList();
  tagList.value = res.data;
}

// 自定义上传请求
const customUploadRequest: UploadRequestHandler = (
  options: UploadRequestOptions
) => {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append("file", file);
  console.log(formData);

  return new Promise((resolve, reject) => {
    fetch("http://172.16.0.6:9000/api/common/newsUpload", {
      method: "post",
      body: formData,
      headers: {
        Authorization:
          "Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6Inh1ZGFkYSIsInVzZXJJZCI6ImE2NzZkYWZkNzVkYzExZWY4ZjUyMDAxNjNlMDEyMzA1IiwiZXhwIjoxNzI3Njc5NjQ2fQ.6ft7Qi_fu1Jcvk3aMB9PASIRnn7Hcrt53RwJ5gLpCCM"
      }
    })
      .then(res => {
        if (res.ok) {
          return res.json(); // 解析 JSON 响应
        } else {
          throw new Error("Upload failed");
        }
      })
      .then(data => {
        ruleForm.coverImg = data.data;
      })
      .catch(err => {
        console.error(err); // 处理错误
        onError(err); // 调用 onError
      });
  });
};
const beforeUpload = (file: File) => {
  console.log(file.type);
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 10;

  if (!isImage) {
    ElMessage({
      message: "上传图片只能是 JPG、PNG 格式!",
      type: "error"
    });
  }
  if (!isLt2M) {
    ElMessage({
      message: "上传图片大小不能超过 10MB!",
      type: "error"
    });
  }
  return isImage && isLt2M;
};
/* 确认发布 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let data = { ...ruleForm };
      console.log(JSON.stringify(data));

      console.log(data);
      publishArticle(JSON.stringify(data))
        .then(res => {
          ElMessage({
            message: "发布成功",
            type: "success"
          });
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
/* 清空内容 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  formEl.resetFields();
};
defineExpose({ open });
</script>
<style lang="scss" scoped>
::v-deep .el-textarea__inner {
  height: 210px;
}

.btn {
  ::v-deep .el-form-item__content {
    justify-content: flex-end;
  }
}

.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
